import { ref } from "vue"
import store from "@/store"
import { defineStore } from "pinia"
import { useTagsViewStore } from "./tags-view"
import { useSettingsStore } from "./settings"
import { getToken, removeToken, setToken } from "@/utils/cache/cookies"
import { resetRouter } from "@/router"
import { loginApi } from "@/api/login"
import { type LoginRequestData } from "@/api/login/types/login"

export const useUserStore = defineStore(
  "user",
  () => {
    const token = ref<string>(getToken() || "")
    const roles = ref<string[]>([])
    const username = ref<string>("")

    const tagsViewStore = useTagsViewStore()
    const settingsStore = useSettingsStore()

    /** 登录 */
    const login = async ({ username, password, code }: LoginRequestData) => {
      const { body } = await loginApi({ username, password, code })
      setToken(body.token)
      token.value = body.token
      roles.value = body.roles || []
    }

    /** 获取用户详情 */
    const getInfo = () => {}

    /** 模拟角色变化 */
    const changeRoles = async (role: string) => {
      console.log(role)
    }

    /** 登出 */
    const logout = () => {
      removeToken()
      token.value = ""
      roles.value = []
      resetRouter()
      _resetTagsView()
    }

    /** 重置 Token */
    const resetToken = () => {
      removeToken()
      token.value = ""
      roles.value = []
    }

    /** 重置 Visited Views 和 Cached Views */
    const _resetTagsView = () => {
      if (!settingsStore.cacheTagsView) {
        tagsViewStore.delAllVisitedViews()
        tagsViewStore.delAllCachedViews()
      }
    }
    return { token, roles, username, login, getInfo, changeRoles, logout, resetToken }
  },
  {
    persist: {
      storage: localStorage
    }
  }
)

/** 在 setup 外使用 */
export function useUserStoreHook() {
  return useUserStore(store)
}
